package com.ruoyi.ucenter.service.impl;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.ucenter.config.BeanCode;
import com.ruoyi.ucenter.config.CodeConfig;
import com.ruoyi.ucenter.service.ISmsCodeService;
import com.ruoyi.ucenter.utils.FormUtils;
import com.ruoyi.ucenter.utils.HttpUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * @author : 张怀秋
 **/
@Service
@EnableConfigurationProperties({CodeConfig.class})
public class SmsCodeServiceImpl implements ISmsCodeService {
    @Resource
    private RedisCache redisCache;

    @Resource
    private BeanCode beanCode;

    /**
     * 发送短信
     *
     * @param phone 手机
     * @return 返回状态
     */
    @Override
    @SuppressWarnings("all")
    public AjaxResult sendValidateCode(String phone) {
        if (!FormUtils.isMobile(phone)) {
            return AjaxResult.error("务必输入合法的手机号码!");
        }
        // 生成验证码
        String validateCode = RandomStringUtils.randomNumeric(4);
        // 存入redis 过期时间5分钟
        redisCache.setCacheObject("phone:code:" + phone, validateCode, 5, TimeUnit.MINUTES);


        String host = "https://dfsns.market.alicloudapi.com";
        String path = "/data/send_sms";
        String method = "POST";

        //发送验证码
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "APPCODE " + beanCode.getCodeBean().get("AppCode"));
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<>();
        Map<String, String> bodys = new HashMap<>();
        bodys.put("content", "code:" + validateCode);
        bodys.put("template_id", "CST_ptdie100");
        bodys.put("phone_number", phone);
//
        try {
            HttpResponse response = HttpUtils.doPost(
                    host,
                    path,
                    method,
                    headers,
                    querys,
                    bodys);
            System.out.println(response.toString());
//            获取response的body
            System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("验证码发送失败！");
        }
        return AjaxResult.success();
    }

    @Override
    public AjaxResult sendMailCode(String mail) throws MessagingException {

        // 邮件服务器设置
        String smtpHost = "smtp.163.com";
        String smtpPort = "465"; // 或者其它SMTP端口
        String senderEmail = "qq734665970@163.com";
        String senderPassword = "SELNAMJBUKEOFHGZ";

        // 创建Properties对象
        Properties props = new Properties();
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);

        // 创建Session实例
        Authenticator auth = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, senderPassword);
            }
        };
        Session session = Session.getInstance(props, auth);

        // 生成验证码
        String validateCode = RandomStringUtils.randomNumeric(6);
        // 创建Message对象
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(senderEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mail));
        message.setSubject("验证码邮件");
        message.setText("您的验证码是: " + validateCode + " 5分钟内有效");
        redisCache.setCacheObject("mail:code:" + mail, validateCode, 5, TimeUnit.MINUTES);

        // 发送邮件
        Transport.send(message);
        return AjaxResult.success();
    }

    @Override
    public Boolean checkCode(String redisKey, String code) {
        String cacheCode = redisCache.getCacheObject(redisKey);
        if (cacheCode == null) {
            throw new RuntimeException("验证码已过期");
        }
        return cacheCode.equals(code);
    }

}
